from flask import Blueprint, request, jsonify
from app.err_no import errno_no
import json, traceback
from app.metrics.jwt_token import JwtTokenError
from app.metrics.authentication_tool import jwtToken
from loguru import logger
from app.db import dbUserLogin
from app.db.dbDiningQuery import queryDiningName, queryAllDiningNo, queryDiningInfoByNo
from app.db.dbStallQuery import queryStallName
from app.db.mongoClient import MongoError
from app.db import dbServerQuery
from app.settings.base import super_administrator


blueprint = Blueprint('user_login', __name__, url_prefix='/api/user')


@blueprint.route('/v1/login', methods=['POST'])
def login():
    j_data = json.loads(request.data)
    userName = j_data.get('userName')
    userPwd = j_data.get('userPwd')
    # isalnum()判断是否数字和字母的组合 以下内容可以通过 '11'  'dd'   '1ddas'
    if userName is None or len(userName) <= 0 or userName.isalnum() is False\
        or userPwd is None or userPwd.isalnum() is False:
        return jsonify(errno_no.ErrUserOrPwdNull.data(None))
    try:
        userInfo = dbUserLogin.verifyUserNamePwd(userName, userPwd)
        # 如果用户被禁用了 则返回
        if userInfo is False:
            data = {'error': '此用户已被禁用'}
            return jsonify(errno_no.ErrServerPermissionDenied.data(data))

        if userInfo is None:
            return jsonify(errno_no.ErrUserOrPwd.data(None))
            
        tokenInfo = {
            'userId': userInfo.get('userId'),
            'userRoleId': userInfo.get('userRoleId'),
            'userRoleName': userInfo.get('userRoleName'),
            'RelationStallNo': userInfo.get('RelationStallNo')
        }
        token = jwtToken.createToken(tokenInfo)
        if token:
            # 获取关联餐厅号和餐厅名
            RelationDiningNoList = []
            DiningNoList = userInfo.get('RelationDiningNoList')
            if userInfo.get('userRoleName') == super_administrator:
                # 超级管理员获取所有的餐厅号
                DiningNoList = queryAllDiningNo()

            if DiningNoList is not None:
                for id in DiningNoList:
                    dininginfo = {
                        'diningNo': id,
                        'diningName': queryDiningName(id) # 根据餐厅号获取餐厅名
                    }
                    RelationDiningNoList.append(dininginfo)
            # 获取关联档口号和档口名
            RelationStallNo = {}
            reStallNo = userInfo.get('RelationStallNo')
            if reStallNo is not None:
                stallinfo = {
                    'stallNo': reStallNo,
                    'stallName': queryStallName(reStallNo) # 根据档口号获取档口名
                }
                RelationStallNo = stallinfo

            RelationDiningNoStallNoList = []
            if DiningNoList is not None:
                for id in DiningNoList:
                    diningName, stallNos = queryDiningInfoByNo(id)
                    dininginfo = {
                        'diningNo': id,
                        'diningName': diningName,
                        'stallNo': stallNos
                    }
                    RelationDiningNoStallNoList.append(dininginfo)

            allPower = dbServerQuery.queryRolePower()
            rolePower = {}
            resRolePower = userInfo.get('rolePower')
            # resRolePower = ["super_server", "super_dining", "super_stall", "super_user", "order_stats"]
            if resRolePower is not None and allPower is not None:
                for key in resRolePower:
                    if key is not None and len(key) > 0:
                        rolePower[key] = allPower[key]

            returnObj = {
                'token': token,
                'userRoleId': userInfo.get('userRoleId'),
                'userRoleName': userInfo.get('userRoleName'),
                'rolePower': rolePower,
                'rolePowers': resRolePower,
                'RelationDiningNoList': RelationDiningNoList,
                'RelationStallNo': RelationStallNo,
                'RelationDiningNoStallNoList': RelationDiningNoStallNoList
            }
            return jsonify(errno_no.OK.data(returnObj))

        return jsonify(errno_no.ErrServerRuntime.data(None))
    except JwtTokenError as e:
        logger.error(f'登录JwtTokenError异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'登录异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
